import 'package:lib_core/lib_core.dart';

import '../gt_logger_model.dart';
import 'gt_logger_base_filter.dart';
import 'package:tuple/tuple.dart';

/// Author: Shper
/// Created: 2024/2/01
class GTLoggerSensitiveWordsFilter extends GTLoggerBaseFilter {

  // 敏感词 列表
  List<String> sensitiveWords = [];
  // 敏感词正则表达式 列表
  List<Tuple2<RegExp, String>> sensitiveRegex = [];

  GTLoggerSensitiveWordsFilter() {
    // 域名相关
    addSensitiveRegex("[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\\.?", "***");
    // ip 相关
    addSensitiveRegex("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}", "***");
    // key, username, user, password 相关
    addSensitiveRegex("key *[=?:?;?\\s?] *\\S+", "***=***");
    addSensitiveRegex("username *[=?:?;?\\s?] *\\S+", "***=***");
    addSensitiveRegex("user *[=?:?;?\\s?] *\\S+", "***=***");
    addSensitiveRegex("password *[=?:?;?\\s?] *\\S+", "***=***");
    addSensitiveRegex("uid *[=?:?;?\\s?] *\\S+", "***=***");
    addSensitiveRegex("token *[=?:?;?\\s?] *\\S+", "***=***");
  }

  // 增加敏感词列表
  void addSensitiveRegex(String pattern, String replaceStr) {
  sensitiveRegex.add(Tuple2(RegExp(pattern), replaceStr));
  }

  @override
  GTLoggerModel handleFilter(GTLoggerModel logModel) {
    // 非发布包、VERBOSE、DEBUG 级别，不过滤敏感词
    if (!GTLibCore.globalConfig.publishBuild || logModel.level.index <= GTLoggerLevel.debug.index) {
      return logModel;
    }

    // 根据敏感词列表过滤
    for (var element in sensitiveWords) {
      if (logModel.message.contains(element)) {
        logModel.message = logModel.message.replaceAll(element, '***');
      }
    }

    // 根据特殊字符规则查找过滤
    for (Tuple2<RegExp, String> tuple in sensitiveRegex) {
      logModel.message = logModel.message.replaceAll(tuple.item1, tuple.item2);
    }
    return logModel;
  }

}